<!--
 * @Descripttion: 权限菜单树
 * @version:
 * @Author: wl
 * @Date: 2020-06-06 15:27:05
 * @LastEditors: wl
 * @LastEditTime: 2020-06-06 17:19:02
-->
<template>
  <div>
    <el-tree
      ref="tree"
      v-loading="loading"
      :data="pageResult"
      show-checkbox
      node-key="id"
      :default-checked-keys="defaultCheckedKeys"
      :props="defaultProps"
      @check="handleCheck"
    ></el-tree>
  </div>
</template>

<script>
export default {
  name: "MenuTree",
  props: {
    checkedKeys: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      pageResult: [],
      defaultProps: {
        label: "name",
        children: "children"
      },
      loading: false,
      defaultCheckedKeys: []
    };
  },
  watch: {
    checkedKeys(nVal){
      this.setCheckedKeys()
    }
  },
  methods: {
    handleQuery() {
      this.loading = true
      let params={
        where: {bool:true,show:true}
      }
     let param= JSON.stringify(params);
       this.$api.menu.findMenuTree(param).then(res => {
          this.loading = false
          if (res.code == 0) {
            this.pageResult = res.data;
            this.setCheckedKeys()
          } else {
            this.$message({
              message: "操作失败, " + res.msg,
              type: "error"
            });
          }
        });
    },
    handleCheck(node,data){
      let _this = this;

      let ids = this.$refs.tree.getCheckedKeys().concat(_this.$refs.tree.getHalfCheckedKeys())
      this.$emit('check',ids)
    },
    setCheckedKeys(){
      var arr = this.checkedKeys; //后台返回的id组成的数组
      var newArr = [];
      var item = '';
      arr.forEach(item=>{
        this.checked(item,this.pageResult,newArr)
      })
      this.defaultCheckedKeys = newArr;
    },
    checked (id,data,newArr){
      data.forEach((item => {
        if(item.id == id){
          if(!item.children || !item.children.length){
            newArr.push(item.id)
          }
        }else{
          if(item.children && item.children.length){
            this.checked(id,item.children,newArr)
          }
        }
      }))
    }
  },
  mounted(){
    this.handleQuery()
  }
};
</script>
